/** @file GOTHspi.c This file contains the source code for the SPI API of the GOTH
 * Kick-ass Etherboard.
 * 
 * Basic layer for SPI on the Kick-ass Etherboard. This file sets the SPI2-port to a clock of 4 MHz.
 * SPI2 is used for the MAC-EEPROM on the board and an extra peripheral that can be added later on.
 *
 * Keep in mind that, in order to use the EEPROM or the extra peripheral, you also need:
 * For EEPROM:
 *		- GOTHspiEeprom.c
 *		- GOTHspiEeprom.h
 * For the extra peripheral:
 *		- GOTHspiExtra.c
 *		- GOTHspiExtra.h
 *
 *
 * @author Geoffrey Ottoy - Tom Hamelinckx
 * @date 05/07/2011 (last modified)
 *
 * <pre>
 * MODIFICATION HISTORY:
 *
 * Who  Date     Changes
 * ---- -------- ---------------------------------------------------------
 * TH   02/07/11 Created this file.
 * TH   04/07/11 Changed to new API-style (split into 3 (spi, eeprom and extra)
 * TH   05/07/11 Documented and tested
 * </pre>
 * 
 */

#include "GOTHspi.h"

/** Initialize SPI2 for operation.
 * 
 * @return	nothing
 *
 * @warning Attached memory has a maximum allowed clock of 5 MHz! Do not exceed!
 */
 void SPI_InitSpi2(void){
	SPI2STATbits.SPIEN = 0;			 // Disable SPI2 for peace of mind!
	
	//Set prescaling to 2 MHz clock
	SPI2CON1bits.PPRE = 2;			//Primary prescaler: 32 MHz divby4 ==> 8MHz
	SPI2CON1bits.SPRE = 5; 			//Secondary Prescaler: 8 MHz divby4 ==> 2MHz

	SPI2CON1bits.CKE = 1;			//Set clock edge (SDO on CLK active to CLK idle)
	SPI2CON2bits.SPIBEN = 0;		//Disable Enhanced mode!
	
	CNPD4bits.CN48PDE = 0;			//Disable pull-downs on SDI2
	CNPU4bits.CN48PUE = 0;			//Disable pull-ups on SDI2
	RPINR22bits.SDI2R = 41;			//Set SDI2 to RPI41
	RPOR10bits.RP21R = 10;			//Set SDO2 to RP21
	RPOR13bits.RP26R = 11;			//Set SCK2Out to RP26 (Out because it's master)	
	
	SPI2STATbits.SPIROV = 0; 		//Clear SPI Overflow!
	SPI2CON1bits.MSTEN = 1; 		//Enable SPI2 as master
	SPI2STATbits.SPIEN = 1; 		//Enable SPI2!
	

 
 }

/** Send data to the selected SPI2 device and read back its answer.
 * 
 * To keep clocking the device and just waiting for its response, keep sending 0
 *
 * @param	data	One byte of data to send out
 *
 * @return	The response from the readback
 */
unsigned char SPI_TransmitReceive(unsigned char data){
	while(SPI2STATbits.SPITBF == 1);
	SPI2BUF = data;
	while(!SPI2STATbits.SPIRBF);
	return SPI2BUF;
}

